package org.teamh.game.repository;

import java.io.File;
import java.util.HashMap;

/**
 * This class is responsible for the temporary storage of map files on the local
 * hard drive. Those temporary files will be deleted when the system is closing.
 * 
 * @author richard
 * 
 */
public class MapRepository {

	private static final HashMap<String, MapEntry> cache = new HashMap<String, MapEntry>();
	
	private MapRepository() {}
	
	/**
	 * Checks, if the file with the specific name is already existing. 
	 * @param name
	 * @return
	 */
	public static boolean contains(String name) {
		return cache.containsKey(name);
	}
	
	/**
	 * Returns the backgroundimage file, if exists, null otherwise. 
	 * @param name
	 * @return
	 */
	public static File getPicture(String name) {
		MapEntry e = cache.get(name);
		if(e != null) {
			return e.getPicture();
		}
		
		return null;
	}
	
	/**
	 * Reutrn the map file if exists, else otherwise. 
	 * @param name
	 * @return
	 */
	public static File getMap(String name) {
		MapEntry e = cache.get(name);
		if(e != null) {
			return e.getMap();
		}
		
		return null;
	}
	
	/**
	 * Puts a new object into the list of temporary files. If the file already exists, it is overridden. 
	 * @param name
	 * @param picture
	 * @param map
	 */
	public static void put(String name, File picture, File map) {
		if(cache.containsKey(name)) {
			getMap(name).delete();
			getPicture(name).delete();
		}
		
		cache.put(name, new MapEntry(picture, map));
	}
	
	/**
	 * Deletes all the temporary file, which are currently managed by the repository. 
	 */
	public static void clear() {
		String[] buf = new String[cache.size()];
		int i = 0;
		for(String name : cache.keySet()) {
			buf[i] = name;
			i++;
		}
		
		for (int j = 0; j < buf.length; j++) {
			cache.remove(buf[j]);
		}
	}

}
